package com.lyz.myself.filter.annotation;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: myself
 * @Date: 2019/1/9 12:02
 * @Author: Mr.Deng
 * @Description:
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER= LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否存在注解
        if(!(handler instanceof HandlerMethod)){
            LOGGER.info("不是HandlerMethod类型，则无需检查");
            return true;
        }
        HandlerMethod method = (HandlerMethod)handler;
        boolean hasLoginAnnotation=method.getMethod().isAnnotationPresent(Priv.class);
        if(!hasLoginAnnotation){
            //不存在Priv注解，则直接通过
            LOGGER.info("不存在Priv，则直接通过");
            return true;
        }
        Priv loginRequired=method.getMethod().getAnnotation(Priv.class);
        //2.required=false,则无需检查是否登录
        if(!loginRequired.login()){
            LOGGER.info("login=false,无需检查是否登录");
            return true;
        }else{
            //3.登录状态检查,使用response返回指定信息
            SessionKey key = new WebSessionKey(request,response);
            Session se = SecurityUtils.getSecurityManager().getSession(key);
            Object obj = se.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
            if(obj != null){
                return true;
            }else{
                LOGGER.info("login=true,需检查是否登录");
                response.getWriter().append("you need login!");
                return false;
            }
        }

    }
}
